define(["Zepto", 
        "underscore", 
        "Backbone", 
        "Handlebars",  
        "text!templates/register/register.html",
        "models/utente",
        "models/session",
        "views/common/menuview",
        "collections/universitacollection",
        "collections/facoltacollection",
        "collections/corsolaureacollection",
], function($, _, Backbone, Handlebars, template, Utente, Session, MenuView, UniversitaCollection, FacoltaCollection, CorsolaureaCollection) {
	
    var RegisterPage = Backbone.View.extend({

        template: Handlebars.compile(template),
        
      
        render: function(eventName) {
            this.$el.html(this.template);
            
            // menu top
			this.menutop = new MenuView({
				el : $('#menu', this.el),
				model : this.model
			});
			this.menutop.render();
            

            self = this;
            var uniList = new UniversitaCollection();
            if (navigator.geolocation) {
                var location_timeout = setTimeout("geolocFail()", 10000);
                navigator.geolocation.getCurrentPosition(
                    function(position) {
                        clearTimeout(location_timeout);
                        var lat = position.coords.latitude;
                        var lng = position.coords.longitude;
                        function calculateDistance(lat1, lon1, lat2, lon2) {
                            var R = 6371; // km
                            var dLat = lat2-lat1;
                            dLat = dLat*Math.PI/180;
                            var dLon = lon2 - lon1;
                            dLon = dLon*Math.PI/180;
                            lat1R = lat1*Math.PI/180;
                            lat2R = lat2*Math.PI/180;
                            var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
                                  Math.cos(lat1R) * Math.cos(lat2R) * 
                                  Math.sin(dLon / 2) * Math.sin(dLon / 2); 
                            var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); 
                            var d = R * c;
                            return d;   
                            /* Number.prototype.toRad = function() {
                              return this * Math.PI / 180;
                            }*/
                        }
                        uniList.fetch({
                            success: function(data) {
                                uniList.each(function(uni){ 
                                    var dist = calculateDistance(lat, lng, uni.get("latitudine"), uni.get("longitudine"));
                                    uni.set({ distanza: dist });
                                });
                                // in UniversitaCollection ho definito un metodo Comparator
                                // ordino la lista delle università in base alla distanza più vicina all'utente
                                uniList.sort(uniList.comparator);
                                uniList.each(
                                    function(univ) {
                                        ﻿$('#universita').append('<option value="' + univ.get('objectId') + '">' + univ.get('nome') + '</option>');
                                    });
                                $('#universita').children('option').first().html('');
                                $('#universita').removeAttr('disabled');
                                $('#universita').scroller({
                                    preset: 'select',
                                    theme: 'android-ics light',
                                    display: 'modal',
                                    mode: 'scroller'
                                });
                            }
                        });
                    },
                    function(error) {
                        alert('Error getting current position');
                        clearTimeout(location_timeout);
                    }
                );
            }else{
                //Non è presente il servizio di geolocalizzazione
            } 

            return this;
        },

        postRender: function(eventName) {
            // $('#facolta').scroller({
            //     preset: 'select',
            //     theme: 'android-ics light',
            //     display: 'modal',
            //     mode: 'scroller'
            // });

            // $('#corsolaurea').scroller({
            //     preset: 'select',
            //     theme: 'android-ics light',
            //     display: 'modal',
            //     mode: 'scroller'
            // });

           
        },


        events: {
            'click #registerbutton': 'register',
            'change #universita' : 'getfaculties',
            'change #facolta' : 'getcorsilaurea',
            'touchstart .button': 'over',
            'touchend .button': 'left',
            'touchcancel .button': 'left',
            'touchstart button': 'over',
            'touchend button': 'left',
            'touchcancel button': 'left'
        },

        getfaculties: function(event) {
            $('#facolta').scroller('destroy');
            $('#facolta').empty();
            $('#facolta').attr('disabled', true);
            $('#facolta').append('<option value="" selected>Loading...</option>');
            
            var facList = new FacoltaCollection();
            facList.fetch({
                query : {
                    universita: {"__type":"Pointer","className":"universita","objectId":$('#universita').val()}
                },
                success: function(data) {
                    facList.each(
                        function(fac) {
                            ﻿$('#facolta').append('<option value="' + fac.get('objectId') + '">' + fac.get('nome') + '</option>');
                        });
                    $('#facolta').children('option').first().html('');
                    $('#facolta').removeAttr('disabled');
                    $('#facolta').scroller({
                        preset: 'select',
                        theme: 'android-ics light',
                        display: 'modal',
                        mode: 'scroller'
                    });
                }
            });
        },

        getcorsilaurea: function(event) {
            
            $('#corsolaurea').scroller('destroy');
            $('#corsolaurea').empty();
            $('#corsolaurea').attr('disabled', true);
            $('#corsolaurea').append('<option value="" selected></option>');
            
            var cdlList = new CorsolaureaCollection();
            cdlList.fetch({
                query : {
                    facolta: {"__type":"Pointer","className":"facolta","objectId":$('#facolta').val()}
                },
                success: function(data) {
                    cdlList.each(
                        function(cdl) {
                            ﻿$('#corsolaurea').append('<option value="' + cdl.get('objectId') + '">' + cdl.get('nome') + '</option>');
                        });
                    $('#corsolaurea').children('option').first().html('');
                    $('#corsolaurea').removeAttr('disabled');
                    $('#corsolaurea').scroller({
                        preset: 'select',
                        theme: 'android-ics light',
                        display: 'modal',
                        mode: 'scroller'
                    });
                }
            });
        },

        register: function(event) {

        	var nome = $('#nome').val();
			var cognome = $('#cognome').val();
			var email = $('#email').val();
			var matricola = $('#matricola').val();
			var corsolaurea = $('#corsolaurea').val();
            var username = $('#username').val();
			var password = $('#password').val();
			var fax = $('#fax').val();
			var telefono = $('#telefono').val();
			var www = $('#www').val();
			var isdocente = $('#radio-2').attr('checked') == true ? true : false;

            var universita = $('#universita').val();
            var facolta = $('#facolta').val();
            var corsolaurea = $('#corsolaurea').val();

            alert($('#photo').attr('src'));

            $.ajax({
                url: 'https://api.parse.com/1/files/'+ (new Date()).getTime() +'.jpg',
                dataType: 'json',
                type: 'POST',
                fileUploadMethod: 'raw',
                processData: false,
                contentType: 'image/jpeg',
                data: $('#photo').attr('url'),
                headers : {
                  "X-Parse-Application-Id" : "0dIPUo9QsGjbp2G0H8qXB7tn8kqSSR6GiGkFm75x",
                  "X-Parse-REST-API-Key" : "MIOI1uSRp8INLA9C7BFKSBRdimGN3fJvkY8me62r"
                },
                success: function(data, status, xhr) { 
                    alert(xhr.status);
                    alert(xhr.responseText);
                    alert(data.name);
                    alert(data.url);
                    var utente = '{"username":"'+username
                        +'","password":"'+password
                        +'","nome":"'+nome
                        +'","cognome":"'+cognome
                        +'","email":"'+email
                        +'","fax":"'+fax
                        +'","telefono":"'+telefono
                        +'","www":"'+www
                        +'","matricola":"'+matricola
                        +'","isdocente":'+isdocente
                        +',"immagine":{"__type":"File","name":"'+data.name
                        +'"},"universita":{"__type":"Pointer","className":"universita","objectId":"'+universita
                        +'"},"facolta":{"__type":"Pointer","className":"facolta","objectId":"'+facolta
                        +'"},"corsolaurea":{"__type":"Pointer","className":"corsolaurea","objectId":"'+corsolaurea+'"}}';

                    //alert (utente);

                    $.ajax({
                        url: 'https://api.parse.com/1/users',
                        type: 'POST',
                        dataType: 'json',
                        contentType: 'application/json',
                        data: utente,
                        headers : {
                          "X-Parse-Application-Id" : "0dIPUo9QsGjbp2G0H8qXB7tn8kqSSR6GiGkFm75x",
                          "X-Parse-REST-API-Key" : "MIOI1uSRp8INLA9C7BFKSBRdimGN3fJvkY8me62r"
                        },
                        success: function(data, status, xhr) { 
                          //alert(xhr.status);
                          //alert(xhr.responseText);
                          alert('Registrazione avvenuta con successo');

                          // Dopo la corretta registrazione effettua il login
                          Session.login({"username":username,"password":password});

                        },    
                        error: function(xhr, errorType, error) {
                          //alert('Errore: ' + xhr + '::::' + error + '::::' + errorType);
                          //alert(xhr.status);
                          alert(xhr.responseText);
                        }
                    });
                },    
                error: function(xhr, errorType, error) {
                  //alert('Errore: ' + xhr + '::::' + error + '::::' + errorType);
                  //alert('Error' + xhr.status);
                  alert(xhr.responseText);
                }
              });


            
		 //	window.history.back();
		 	
		 	
			/*utente.save({
	            success:function () {
	               alert('utente creato');
	               Backbone.history.back();
	            }
	        });
	        return false;*/
        },

        over: function(event) {
            $(event.currentTarget).addClass('fake-active');
        },

        left: function(event) {
            $(event.currentTarget).removeClass('fake-active');
        }
        
       
    });

    return RegisterPage;

});

